package com.mallcloud.mall.admin.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mallcloud.mall.admin.api.entity.SysDept;
import com.mallcloud.mall.admin.api.entity.SysDeptRelation;
import com.mallcloud.mall.admin.service.SysDeptRelationService;
import com.mallcloud.mall.admin.service.SysDeptService;
import com.mallcloud.mall.common.core.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(tags = "部门管理模块")
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
public class SysDeptController {
	private final SysDeptRelationService relationService;
	private final SysDeptService sysDeptService;

	@ApiOperation("通过ID查询")
	@GetMapping("/{id}")
	public R<SysDept> getById(@PathVariable Long id) {
		return R.ok(sysDeptService.getById(id));
	}

	@ApiOperation("查询全部部门")
	@GetMapping("/list")
	public R<List<SysDept>> list() {
		return R.ok(sysDeptService.list());
	}

	@ApiOperation("返回树形菜单集合")
	@GetMapping("/tree")
	public R<List<Tree<Long>>> getTree(String deptName) {
		return R.ok(sysDeptService.selectTree(deptName));
	}

	@ApiOperation("添加")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_add')")
	public R<Boolean> save(@Valid @RequestBody SysDept sysDept) {
		return R.ok(sysDeptService.saveDept(sysDept));
	}

	@ApiOperation("删除")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_dept_del')")
	public R<Boolean> removeById(@PathVariable Long id) {
		return R.ok(sysDeptService.removeDeptById(id));
	}

	@ApiOperation("编辑")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
	public R<Boolean> update(@Valid @RequestBody SysDept sysDept) {
		return R.ok(sysDeptService.updateDeptById(sysDept));
	}

	@ApiOperation("查收子级列表")
	@GetMapping("/getDescendantList/{deptId}")
	public R<List<SysDeptRelation>> getDescendantList(@PathVariable Long deptId) {
		return R.ok(relationService.list(Wrappers.<SysDeptRelation>lambdaQuery().eq(SysDeptRelation::getAncestor, deptId)));
	}

}
